"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

from msnp.persistence import FileAccessor

class Settings():
    """This class contains settings, an instance represents a settings file.
    
    Parameters:
        __lastLoginUsername: A String containing the name of the user that logged in the last time.
        __userSettings: A list of UserSetting objects containing the settings of all users. 
    """
    def __init__(self):
        """The init method."""
        self.__lastLoginUsername = ""
        self.__userSettings = None
        
    def getLastLoginUsername(self):
        """Returns the parameter __lastLoginUsername."""
        return self.__lastLoginUsername
    
    def setLastLoginUsername(self, username):
        """Sets the parameter __lastLoginUsername to the given parameter."""
        if username != None:
            username = unicode(username)
        self.__lastLoginUsername = username
        
    def getUserSettings(self):
        """Returns the parameter __userSettings."""
        return self.__userSettings
    
    def getCurrentUserSettings(self):
        """Returns the UserSettings object for the user that logged in last."""
        if self.__userSettings != None:
            for userSetting in self.__userSettings:
                if userSetting.getUsername() == self.__lastLoginUsername:
                    return userSetting
        return None
    
    def setCurrentUserSettings(self, newUserSettings):
        """Sets the given UserSetting as the settings for the current user."""
        if self.__userSettings != None:
            for userSetting in self.__userSettings:
                if userSetting.getUsername() == self.__lastLoginUsername:
                    self.__userSettings.remove(userSetting)
                    break
        else:
            self.__userSettings = []
        self.__userSettings.append(newUserSettings)
    
    def setUserSettings(self, userSettings):
        """Set the parameter __userSettings to the given one."""
        self.__userSettings = userSettings
        
    def addUserSettings(self, userSetting):
        """Adds the given user settings to the parameter __userSettings."""
        if self.__userSettings == None:
            self.__userSettings = []
        self.__userSettings.append(userSetting)
        
    def getFirstFreeStartPort(self):
        """Returns a port, that is not already assigned to a user in a setting.
        
        Checks the ports of all user settings and takes the smallest one
        higher than 20000 that is not already assigned.
        
        Returns:
            An integer containing the first free port is returned."""
        freePort = 20000
        if self.__userSettings != None:
            i = 0
            for userSetting in self.__userSettings:
                tmpStartPort = long(userSetting.getStartPort())
                if tmpStartPort >= freePort or i == 0:
                    freePort = long(userSetting.getEndPort()) + 1
        return str(freePort)
        
    def initSettingsForNewUser(self, username):
        """Initializes the settings for the given username.
        
        Sets the parameter __lastLoginUsername, assigns ports to the new user settings
        and adds them to the parameter __userSettings.
        
        Args:
            username: A String containing the name of the new user.
        """
        self.__lastLoginUsername = username
        usersettings = UserSettings()
        usersettings.setUsername(username)
        startPort = self.getFirstFreeStartPort()
        endPort = str(long(startPort) + 7)
        usersettings.setStartPort(startPort)
        usersettings.setEndPort(endPort)
        self.addUserSettings(usersettings)
    
    
class UserSettings():
    """This class contains the settings of one user.
    
    Parameters:
        __username: A String containing the name of the user that logged in the last time.
        __playerDatabaseSettings: A DatabaseSettings objects containing the player database settings for the user.
        __msnpDatabaseSettings: A DatabaseSettings objects containing the ptp database settings for the user.
        __mediaDatabaseSettings: A DatabaseSettings objects containing the media player database settings for the user.
        __groupSettingsList: A list of GroupSettings objects containing the group settings for the user.
        __lastPlayerSynch: A LastPlayerSynch object.
        __startPort: An integer value indicating the first reserved port for the user.
        __endPort: An integer value indicating the last reserved port for the user.
        __amarokConfFilePath: A String containing the path to the amarok configuration file.
    """
    def __init__(self):
        """The init method."""
        self.__username = None
        self.__playerDatabaseSettings = DatabaseSettings()
        self.__msnpDatabaseSettings = DatabaseSettings()
        self.__mediaDatabaseSettings = DatabaseSettings()
        self.__groupSettingsList = []
        #last time the synch button was pressed
        self.__lastPlayerSynch = LastPlayerSynch()
        self.__startPort = "20000"
        self.__endPort = "20007"
        #TODO not stored in xml yet
        self.__amarokConfFilePath = FileAccessor.getHomeDirectory() + "/.msnp_amarok.conf"
        
    def setUsername(self, username):
        """Sets the parameter __username to the given one."""
        if username != None:
            username = unicode(username)
        self.__username = username
        
    def getUsername(self):
        """Returns the parameter __username."""
        return self.__username
    
    def setPlayerDatabaseSettings(self, pds):
        """Sets the parameter __playerDatabaseSettings to the given one."""
        self.__playerDatabaseSettings = pds
        
    def getPlayerDatabaseSettings(self):
        """Returns the parameter __playerDatabaseSettings."""
        return self.__playerDatabaseSettings
    
    def setMSNPDatabaseSettings(self, dbs):
        """Sets the parameter __msnpDatabaseSettings to the given one."""
        self.__msnpDatabaseSettings = dbs
        
    def getMSNPDatabaseSettings(self):
        """Returns the parameter __msnpDatabaseSettings."""
        return self.__msnpDatabaseSettings
    
    def setMediaDatabaseSettings(self, dbs):
        """Sets the parameter __mediaDatabaseSettings to the given one."""
        self.__mediaDatabaseSettings = dbs
        
    def getMediaDatabaseSettings(self):
        """Returns the parameter __mediaDatabaseSettings."""
        return self.__mediaDatabaseSettings
    
    def getGroupSettingsList(self):
        """Returns the parameter __groupSettingsList."""
        return self.__groupSettingsList
    
    def setGroupSettingsList(self, list):
        """Sets the parameter __groupSettingsList to the given one."""
        self.__groupSettingsList = list
    
    def addGroupSettings(self, groupSettings):
        """Adds the given group settings to the parameter __groupSettingsList."""
        self.__groupSettingsList.append(groupSettings)
        
    def setLastPlayerSynch(self, time):
        """Sets the parameter __lastPlayerSynch to the given one."""
        self.__lastPlayerSynch = time
        
    def getLastPlayerSynch(self):
        """Returns the parameter __lastPlayerSynch."""
        return self.__lastPlayerSynch
    
    def setStartPort(self, startPort):
        """Sets the parameter __startPort to the given one."""
        self.__startPort = startPort
        
    def getStartPort(self):
        """Returns the parameter __startPort."""
        return self.__startPort
    
    def setEndPort(self, endPort):
        """Sets the parameter __endPort to the given one."""
        self.__endPort = endPort
        
    def getEndPort(self):
        """Returns the parameter __endPort."""
        return self.__endPort
    
    def getAmarokConfFilePath(self):
        """Returns the parameter __amarokConfFilePath."""
        return self.__amarokConfFilePath
    
    def setAmarokConfFilePath(self, path):
        """Sets the parameter __amarokConfFilePath to the given one."""
        self.__amarokConfFilePath = path
    
    def isSynchOnForGroup(self, groupname, ownername, synchOut=True):
        """Returns whether synchronization is set for the given group.
        
        Retrieves the given group and checks the parameter isSynchOut or isSynchIn,
        depending on the given parameter synchOut.
        
        Args:
            groupname: A String containing the group name.
            ownername: A String containing the owner name.
            synchOut: A boolean value which synchronization should be checked. Default True.
        
        Returns:
            True is returned if the given synchronization is on for the given group, otherwise false.
        """
        if self.__groupSettingsList != None and len(self.__groupSettingsList) > 0:
            for groupSettings in self.__groupSettingsList:
                if groupname == groupSettings.getGroupname() and ownername == groupSettings.getOwnername():
                    if synchOut:
                        return groupSettings.isSynchOut()
                    else:
                        return groupSettings.isSynchIn()
        return False
        
class DatabaseSettings():
    """This class contains the database settings.
    
    Parameters:
        __player: A String containing the name of the player. Is empty for the ptp database. Default empty.
        __host: A String containing the host where the database is located. Default empty.
        __user: A String containing the name of the user for the database. Default empty.
        __password: A String containing the password corresponding to the user. Default empty.
        __schema: A String containing the schema of the database. Default empty.
    """
    def __init__(self, host="", user="", password="", schema="", player=""):
        """The init method."""
        #for the msnp db settings the player-field is empty
        self.__player = player
        if host != None:
            host = unicode(host)
        if user != None:
            user = unicode(user)
        if password != None:
            password = unicode(password)
        if schema != None:
            schema = unicode(schema)
        self.__host = host
        self.__user = user
        self.__password = password
        self.__schema = schema
        
    def getPlayer(self):
        """Returns the parameter __player."""
        return self.__player
    
    def getHost(self):
        """Returns the parameter __host."""
        return self.__host
    
    def getUser(self):
        """Returns the parameter __user."""
        return self.__user
    
    def getPassword(self):
        """Returns the parameter __password."""
        return self.__password
    
    def getSchema(self):
        """Returns the parameter __schema."""
        return self.__schema
    
    def isComplete(self):
        """Checks whether the parameters __host, __user and __schema are set."""
        if len(self.__host) > 0 and len(self.__user) > 0 and len(self.__schema) > 0:
            return True
        return False
    
    def deleteDBSettings(self):
        """Resets the parameters __host, __password, __schema and __user."""
        self.__host = ""
        self.__password = ""
        self.__schema = ""
        self.__user = ""
    
class GroupSettings():
    """This class contains group settings.
    
    Parameters:
        __groupname: A String containing the group name.
        __ownername: A String containing the owner name.
        __isSynchOut: A boolean value, True if the inwards synchronization is set on.
        __isSynchIn: A boolean value, True if the outwards synchronization is set on.
    """
    def __init__(self, groupname, ownername, isSynchOut, isSynchIn):
        """The init method."""
        if groupname != None:
            groupname = unicode(groupname)
        if ownername != None:
            ownername = unicode(ownername)
        self.__groupname = groupname
        self.__ownername = ownername
        self.__isSynchOut = isSynchOut
        self.__isSynchIn = isSynchIn
        
    def getGroupname(self):
        """Returns the parameter __groupname."""
        return self.__groupname
    
    def getOwnername(self):
        """Returns the parameter __ownername."""
        return self.__ownername
    
    def isSynchOut(self):
        """Returns the parameter __isSynchOut."""
        return self.__isSynchOut
    
    def isSynchIn(self):
        """Returns the parameter __isSynchIn."""
        return self.__isSynchIn
    
class LastPlayerSynch():
    """This class contains information about the last synchronization towards the player.
    
    Parameters:
        __lastProcessedId: An integer value containing the highest id that was already processed. Default -1.
        __date: A String containing the date when the last synchronization was performed. Default empty.
    """
    def __init__(self, lastProcessedId= -1, date=""):
        """The init method."""
        self.__lastProcessedId = lastProcessedId
        self.__date = date
        
    def getLastProcessedId(self):
        """Returns the parameter __lastProcessedId."""
        return self.__lastProcessedId
    
    def getDate(self):
        """Returns the parameter __date."""
        return self.__date
